package com.ruoyi.network.message;


import com.ruoyi.common.utils.HexUtil;

public class SendMessage {

    /**
     * 包头
     */
    private String frameHeader = "AA";

    private String packageTotal="01";

    private String packageIndex="00";

    private String dataLength;

    private String cmd;

    private String dataHex;

    private String crcHight;

    private String crcLow;

    public SendMessage(int packageCount, int packageIndex, String cmd, String dataHex){

        this.packageTotal = Integer.toHexString(packageCount);
        if(this.packageTotal.length()%2==1){
            this.packageTotal = "0"+this.packageTotal;
        }


        this.packageIndex = Integer.toHexString(packageIndex);
        if(this.packageIndex.length()%2==1){
            this.packageIndex = "0"+this.packageIndex;
        }

        this.cmd = cmd;
        this.dataHex = dataHex;
        if(this.dataHex==null){
            this.dataLength ="00";
        }else{
            this.dataLength = Integer.toHexString(dataHex.length() / 2);
            if(this.dataLength.length()%2==1){
                this.dataLength = "0"+this.dataLength;
            }
        }


    }

    public String toHexString(){

        StringBuilder sb = new StringBuilder();
        sb.append(this.frameHeader);
        sb.append(this.packageTotal);
        sb.append(this.packageIndex);
        sb.append(this.dataLength);
        sb.append(this.cmd);
        sb.append(this.dataHex);

        String prefix = sb.toString();

        //prefix -> byte[]
        byte[] crcBytes = HexUtil.hexStringToByteArray(prefix);

        String crc = HexUtil.getCRC(crcBytes);

        sb.append(crc.substring(2, 4));
        sb.append(crc.substring(0, 2));

        return sb.toString();

    }


    public static void main(String[] args) {

        System.out.println(Integer.toHexString(256));

    }

}
